package com.legolas.consumer.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.legolas.api.service.SeckillService;
import com.legolas.api.utils.ResponseUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @author legolas
 * @date 2020/5/14 15:33
 */
@Service
public class ConsumerSeckillService {

    /**
     * buyGoods方法不进行失败重试操作
     */
    @Reference(version = "1.0.0", timeout = 1000, parameters = {"buyGoods.retries", "0"}, actives = 2000)
    SeckillService seckillService;

    public List getAllGoods() {
        return seckillService.getAllGoods();
    }

    public HttpEntity addGoods(String name, Integer stock) {
        try {
            seckillService.addGoods(name, stock);
            return ResponseUtils.buildOKResponse("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtils.build500Response();
        }
    }

    //TODO 消费端添加事务逻辑无效，需要用到分布式事务
    @Transactional(rollbackFor = Exception.class)
    public HttpEntity buyGoods(Integer id) {
        try {
            int result = seckillService.buyGoods(id);
            if (result > 0) {
                return ResponseUtils.buildOKResponse("买入成功！");
            } else {
                return ResponseUtils.buildOKResponse("库存已空！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtils.buildOKResponse("服务异常！稍后再试！");
        }
    }


    public HttpEntity addStock(Integer id) {
        int result = seckillService.addStock(id);
        if (result > 0) {
            return ResponseUtils.buildOKResponse("当前剩余库存" + result);
        } else {
            return ResponseUtils.buildStringResponse("添加库存失败!", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}
